package pt.isel.lercm.projectmanager.spring.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import pt.isel.lercm.projectmanager.spring.model.Aluno;

@Repository
public class AlunoDAO implements IAlunoDAO {

	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@Override
	public void addObject (Aluno object){
		getSessionFactory().getCurrentSession().save(object);
	}
	
	@Override
	public void updateObject(Aluno object){
		getSessionFactory().getCurrentSession().update(object);
	}
	
	@Override
	public void deleteObject(Aluno object){
		getSessionFactory().getCurrentSession().delete(object);
	}
	
	@Override
	public Aluno getByid(int id) {
		List<Aluno> list = getSessionFactory().getCurrentSession().createQuery("from Aluno where id=?").setParameter(0, id).list();
		
		if (list == null || list.isEmpty()){
			return null;
		}
		
		return list.get(0);
	}

	@Override
	public List<Aluno> getAll() {
		List<Aluno> list = getSessionFactory().getCurrentSession().createQuery("from Aluno").list();
		
		if (list == null || list.isEmpty()){
			return null;
		}
		
		return list;
	}
	
	public Aluno getAlunoByNumero(String numero){
		List<Aluno> list = getSessionFactory().getCurrentSession().createQuery("from Aluno where numero=?").setParameter(0, numero).list();
		
		if (list == null || list.isEmpty()){
			return null;
		}
		
		return list.get(0);
	}
	
	public List<Aluno> getAllByYear(int idAno){
		List<Aluno> list = getSessionFactory().getCurrentSession().createQuery("from Aluno where ano_id=?").setParameter(0, idAno).list();
		
		if (list == null || list.isEmpty()){
			return null;
		}
		
		return list;
	}

}
